include(CMakeParseArguments)

# 检查是否通过 -D 传递了 TARGET 参数
if (DEFINED TARGET)
    set(COPY_DEP_TARGET ${TARGET})
else ()
    message(FATAL_ERROR "Missing 'TARGET' argument.")
endif ()

# 打印接收到的参数，用于调试
message(STATUS "Received TARGET: ${COPY_DEP_TARGET}")

# 定义 copy_dependencies 函数
function(copy_dependencies target)

    # 函数内容
    execute_process(
            COMMAND c:/msys64/usr/bin/ldd.exe ${target}
            OUTPUT_VARIABLE LDD_OUTPUT
            ERROR_VARIABLE LDD_ERROR
            RESULT_VARIABLE LDD_RESULT
    )

    if (NOT LDD_RESULT EQUAL 0)
        message(FATAL_ERROR "Failed to run ldd: ${LDD_ERROR}")
    endif ()

    # message(STATUS "LDD_OUTPUT: ${LDD_OUTPUT}")

    string(REGEX MATCHALL "/[^ ]+\\.dll" DEPENDENCY_PATHS "${LDD_OUTPUT}")
    get_filename_component(TARGET_OUTPUT_DIR ${target} DIRECTORY)

    foreach (DEPENDENCY ${DEPENDENCY_PATHS})
        if (DEPENDENCY MATCHES "/mingw64/")
            # message(STATUS "Converting MSYS2 path: ${DEPENDENCY}")
            # 替换 /mingw64 为 c:/msys64/mingw64
            string(REGEX REPLACE "^/mingw64" "c:/msys64/mingw64" DEPENDENCY_WIN ${DEPENDENCY})
            # message(STATUS "Copying dependency: ${DEPENDENCY_WIN}")
            if(EXISTS ${DEPENDENCY_WIN})
                file(COPY ${DEPENDENCY_WIN} DESTINATION ${TARGET_OUTPUT_DIR})
                get_filename_component(DEST_FILE_NAME ${DEPENDENCY_WIN} NAME)
                set(DEST_FILE "${TARGET_OUTPUT_DIR}/${DEST_FILE_NAME}")
                if(EXISTS ${DEST_FILE})
                    message(STATUS "Successfully copied: ${DEPENDENCY_WIN}")
                else()
                    message(WARNING "Failed to copy: ${DEPENDENCY_WIN}")
                endif()
            endif()
        endif ()
    endforeach ()
endfunction()

# 定义 deploy_qt 函数
function(deploy_qt target)
    get_filename_component(TARGET_OUTPUT_DIR ${target} DIRECTORY)
    # 假设 windeployqt6 在 mingw64 的 bin 目录下
    set(WINDEPLOYQT_PATH "c:/msys64/mingw64/bin/windeployqt6.exe")
    if(NOT EXISTS ${WINDEPLOYQT_PATH})
        message(FATAL_ERROR "windeployqt6 not found at ${WINDEPLOYQT_PATH}")
    endif()

    message(STATUS "Running windeployqt6 for ${target}")
    execute_process(
            COMMAND ${WINDEPLOYQT_PATH} ${target}
            WORKING_DIRECTORY ${TARGET_OUTPUT_DIR}
            RESULT_VARIABLE DEPLOY_RESULT
            ERROR_VARIABLE DEPLOY_ERROR
    )

    if(NOT DEPLOY_RESULT EQUAL 0)
        message(WARNING "Failed to run windeployqt6: ${DEPLOY_ERROR}")
    endif()
endfunction()

# 调用 copy_dependencies 函数
copy_dependencies(${COPY_DEP_TARGET})
# 调用 deploy_qt 函数
deploy_qt(${COPY_DEP_TARGET})